package com.cckj.common.exception;

import com.cckj.common.response.ResultData;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description //TODO  类似401、404、403或者过滤器报错 的异常处理
 * @Author jq
 * @time: 2020/11/2 14:21
 */
@Configuration
public class GlobalErrorController extends BasicErrorController {

    public GlobalErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, new ErrorProperties());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        // springboot 默认封装的返回值
        Map<String, Object> errorAttributes = getErrorAttributes(request, ErrorAttributeOptions.defaults());

        StringBuffer error = new StringBuffer();
        if (errorAttributes.containsKey("path")) {
            error.append("[").append(errorAttributes.get("path").toString()).append("] ");
        }
        error.append(errorAttributes.get("error").toString());
        if (errorAttributes.containsKey("message")) {
            error.append(" : ").append(errorAttributes.get("message").toString());
        }
        HttpStatus status = getStatus(request);
        // 自定义统一返回格式
        ResponseEntity<Map<String, Object>> mapResponseEntity = new ResponseEntity<>(
                new ObjectMapper().convertValue(ResultData.error(status.value(), error.toString()),
                new TypeReference<Map<String, Object>>() {}),
                status
        );

        return mapResponseEntity;
    }

    // 跳转html界面
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("界面错误");
        return super.errorHtml(request, response);
    }

}
